<?php
class Application_Model_Mapper
{
  protected $_dbTableClass;
  protected $_dbTable;
  protected $_model;		/* model name of each Model_Xxx */

  public function __construct()
  {
    $this->_dbTable = new $this->_dbTableClass();
  }

  public function getDbTable()
  {
    return $this->_dbTable;
  }

  public function save(Application_Model_Base $obj)
  {
    $pk = $obj->getPrimaryKey();
    if (!($id = $obj->get($pk))) {
      return $this->getDbTable()->insert($obj->getOptions());
    } 
    else {
      $data = $obj->getOptions();
      unset($data[$pk]);
      return $this->getDbTable()->update($data, "$pk = $id");
    }
  }

  public function findObj($where, Application_Model_Base $obj)
  {
    $row = $this->getDbTable()->fetchRow($where);
    if (0 == count($row)) {
      return;
    }

    if ($row)
      $row = $row->toArray();
    $obj->setOptions($row);
  }

  public function find($id, Application_Model_Base $obj)
  {
    $result = $this->getDbTable()->find($id);
    if (0 == count($result)) {
      return;
    }
    $row = $result->current();
    if ($row)
      $row = $row->toArray();
    $obj->setOptions($row);
  }
  public function delete($id)
  {
    return $this->getDbTable()->delete("id = $id");
  }

  public function fetchAll($where = null, $order = null, $count = null, $offset = null)
  {
    $resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
    $entries   = array();
    foreach ($resultSet as $row) {
      $entry = new $this->_model;
      if ($row)
	$row = $row->toArray();
      $entry->setOptions($row);
      $entries[] = $entry;
    }
    return $entries;
  }
}